from job import Job
from exception import InvalidJobObjectError
from utils.name_generator import generator
import functional
from excutor import ExcutorThread
import time

class Task():

    def __init__(self,controller_name,name=None, jobs=None):
        self.name = name
        if name is None:
            self.name = generator()
        if jobs is None:
            self.jobs = []
        else:
            self.jobs = jobs
        self.controller_name = controller_name
        self.excutors = [ ]
        self.create_at = time.ctime()
        self.next_run = None
        self.once = False

    def addJob(self,job):
        if isinstance(job,Job):
            job.task_name = self.name
            self.jobs.append(job)
        else:
            raise InvalidJobObjectError()

    def removeJob(self,job_name):
        pass

    def run(self,job_name=None):
        if job_name is None:
            ExcutorThread(jobs=self.jobs).start()
        query_jobs = functional.seq(self.jobs).where(lambda x:x.name == job_name)
        if query_jobs.len() > 0:
            t = ExcutorThread(jobs=query_jobs.to_list())
            t.start()
            self.excutors.append(t)


    def __str__(self):
        return 'Task - ' + self.name

    def __repr__(self):
        return 'Task - ' + self.name


